package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.pojo.CartItem;
import com.qf.utils.DBUtils;
import com.qf.utils.SqlUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CarDaoImpl implements CartDao {
    QueryRunner queryRunner = new QueryRunner();

    @Override
    public Long findCountByUidAndPid(String pid, long uid) {
        String sql = SqlUtils.getSql("cart.selectcount");
        try {
            long count = queryRunner.query(DBUtils.getConnection(), sql, new ScalarHandler<>(), uid, pid);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addCart(String pid, long uid, int num) {
        String sql = SqlUtils.getSql("cart.add");
        try {
            queryRunner.insert(DBUtils.getConnection(), sql, new ScalarHandler<>(), uid, pid, num);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public int updateNum(String pid, long uid, int num) {
        String sql = SqlUtils.getSql("cart.update");
        try {
            return queryRunner.update(DBUtils.getConnection(), sql, num, uid, pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<CartItem> findCartByUid(long uid) {
        String sql = SqlUtils.getSql("cart.selectbyuid");
        try {
            List<CartItem> query = queryRunner.query(DBUtils.getConnection(), sql, new BeanListHandler<>(CartItem.class), uid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
